package interpreters;

import java.util.ArrayList;
import java.util.Arrays;

import org.apache.poi.util.ArrayUtil;

import utils.ObjectUtils;
import utils.StringUtils;

public class Weaver {

	String quelle = "";
	String[] separated;
	ClassResponse response;

	public Weaver(String quelle) {
		this.quelle = quelle;
	}

	public void trasform() {
		if (!quelle.equals("") || quelle != null) {
			this.separated = quelle.split(" ");
			// /work about separated[0] schlusselwort
			String schlusselwort = separated[0];
			if (StringUtils.isReservedWord(schlusselwort)) {
				try {
					String methodNameAndParams = StringUtils
							.getReservedWordMeaning(schlusselwort);
					if (validateMethod(methodNameAndParams, quelle)) {
						response = new ClassResponse();
						response.setClassCanonicalPath(getClass(methodNameAndParams));
						response.setMethodName(getMethod(methodNameAndParams));
						response.setArgumentTypes((ArrayList<String>) Arrays
								.asList(getParams()));

					}

				} catch (Exception ex) {

					ex.printStackTrace();

				}
			}

		}
	}

	public boolean validateMethod(String method, String quelle) {
		// For example quelle can be the followin
		// package1.package2.blablablaclass.method(String,Repository)
		String className = quelle.substring(0, quelle.lastIndexOf("."));
		String methodName = quelle.substring(quelle.lastIndexOf(".") + 1,
				quelle.indexOf("("));
		String typesquell = quelle.substring(quelle.indexOf("("),
				quelle.indexOf(""));
		String[] types = typesquell.split(",");

		if (ObjectUtils.methodExist(ObjectUtils.createClassByName(className),
				methodName)) {
			return true;
		} else {
			return false;
		}
	}

	public String getMethod(String quelle) {
		return quelle.substring(quelle.lastIndexOf(".") + 1,
				quelle.indexOf("("));
	}

	public String[] getParams() {
		String typesquell = quelle.substring(quelle.indexOf("("),
				quelle.indexOf(""));
		return typesquell.split(",");

	}

	public String getClass(String quelle) {
		return quelle.substring(0, quelle.lastIndexOf("."));
	}

	public static void main(String[] args) {
		Weaver wea = new Weaver("cd /UML/");
		wea.trasform();

	}
}
